package c926.xiaoduyun.xiaodu.plugin.signature;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.control.Html;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.list.BillList;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;

/**
 * 标准单据列表插件
 */
public class RichTextSignSealPlugin extends AbstractListPlugin implements Plugin {


    @Override
    public void registerListener(EventObject e) {
        // 工具栏项注册点击监听
        Toolbar toolbar = this.getView().getControl("toolbarap");
        toolbar.addItemClickListener(this);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if ("c926_doseal".equalsIgnoreCase(itemKey)) {
            // 获取所选列表数据
            BillList billList = this.getView().getControl("billlistap");
            ListSelectedRowCollection selectedRow = billList.getSelectedRows();
            DynamicObject richText = BusinessDataServiceHelper.loadSingle(selectedRow.get(0).getPrimaryKeyValue(), "c926_test");
            Long orgId = (Long) richText.get("c926_orgfield.id");
            String text = (String) richText.get("c926_largetextfield_tag");
            String signStatus = richText.getString("c926_signstatus");
            if ("B".equals(signStatus)) {
                this.getView().showTipNotification("请勿重复签章！");
                return;
            }
            // 查询对应组织的公章图片地址
            QFilter filter = new QFilter("c926_orgfield", QCP.equals, orgId).and("c926_isdefault", QCP.equals, "1");
            DynamicObject seal = BusinessDataServiceHelper.loadSingle("c926_sealtest", new QFilter[]{filter});
            String imageUrl = (String) seal.get("c926_sealimage");

            // 生成图片的 HTML
            String imageHtml = "<span style=\"position: relative; display: inline-block;\">"
                    + "<img src=\"http://127.0.0.1:8881/ierp/attachment/downloadImage/" + imageUrl +
                    "\" alt=\"盖章图片\" style=\"position: absolute; top: -50px; left: -50px; width: 166px; height: 166px;\" />"
                    + "</span>";

            // 将图片和文本插入到富文本中
            String updatedText = text.replace("盖章", "盖章" + imageHtml);

            // 更新富文本字段内容
            richText.set("c926_largetextfield_tag", updatedText);
            richText.set("c926_signstatus", "B");
            SaveServiceHelper.update(richText);
            this.getView().showSuccessNotification("操作成功！");
            this.getView().updateView();
        }
    }


}